package org.example.queueadmin.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Slf4j
public class SystemConfigService {
    
    private final SystemConfigRepository repository;
    
    public List<SystemConfig> getAllConfigs() {
        return repository.findAll();
    }
    
    public Optional<SystemConfig> getConfig(String key) {
        return repository.findByConfigKey(key);
    }
    
    public String getConfigValue(String key, String defaultValue) {
        return repository.findValueByKey(key).orElse(defaultValue);
    }
    
    public Integer getConfigValueAsInt(String key, Integer defaultValue) {
        try {
            String value = getConfigValue(key, null);
            return value != null ? Integer.parseInt(value) : defaultValue;
        } catch (NumberFormatException e) {
            log.warn("Invalid integer config value for key {}: {}", key, e.getMessage());
            return defaultValue;
        }
    }
    
    public Boolean getConfigValueAsBoolean(String key, Boolean defaultValue) {
        String value = getConfigValue(key, null);
        return value != null ? Boolean.parseBoolean(value) : defaultValue;
    }
    
    @Transactional
    public SystemConfig saveConfig(String key, String value, String description, String valueType) {
        Optional<SystemConfig> existing = repository.findByConfigKey(key);
        
        SystemConfig config;
        if (existing.isPresent()) {
            config = existing.get();
            config.setConfigValue(value);
            config.setDescription(description);
            config.setValueType(valueType);
        } else {
            config = new SystemConfig();
            config.setConfigKey(key);
            config.setConfigValue(value);
            config.setDescription(description);
            config.setValueType(valueType);
        }
        
        return repository.save(config);
    }
    
    @Transactional
    public void deleteConfig(String key) {
        repository.findByConfigKey(key).ifPresent(repository::delete);
    }
    
    // 初始化默认配置
    @Transactional
    public void initializeDefaultConfigs() {
        // 日志清理配置
        saveConfigIfNotExists("log.cleanup.enabled", "true", "是否启用日志自动清理", "BOOLEAN");
        saveConfigIfNotExists("log.cleanup.retention.days", "7", "日志保留天数", "INTEGER");
        saveConfigIfNotExists("log.cleanup.interval.hours", "1", "清理检查间隔（小时）", "INTEGER");
        saveConfigIfNotExists("log.cleanup.batch.size", "1000", "每次清理的批次大小", "INTEGER");
        
        // 消息预览配置
        saveConfigIfNotExists("message.preview.max.length", "200", "消息预览最大长度", "INTEGER");
        saveConfigIfNotExists("message.preview.hex.limit", "50", "二进制消息十六进制显示限制", "INTEGER");
    }
    
    private void saveConfigIfNotExists(String key, String value, String description, String valueType) {
        if (!repository.existsByConfigKey(key)) {
            saveConfig(key, value, description, valueType);
        }
    }
}
